package com.example.myapplication

import android.annotation.SuppressLint
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Bundle
import android.os.PowerManager
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import com.example.myapplication.alarm.AlarmManagerUtils
import com.example.myapplication.databinding.ActivityMainBinding
import com.example.myapplication.wheelview.adapter.WheelAdapter
import com.hqf.guide.NewbieGuide
import com.hqf.guide.model.GuidePage
import kotlinx.coroutines.*
import rx.android.schedulers.AndroidSchedulers
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity(){
    private  val TAG = "MainActivity"
    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)

        val navController = findNavController(R.id.nav_host_fragment_content_main)
        appBarConfiguration = AppBarConfiguration(navController.graph)
        setupActionBarWithNavController(navController, appBarConfiguration)

        binding.fab.setOnClickListener {
//            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                .setAction("Action", null).show()
//            showGuidView1()

            Log.e(TAG, "onCreate: "+timeStamp2Date(System.currentTimeMillis(),null))
        }
        binding.tvGuide.setOnClickListener {
//            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                .setAction("Action", null).show()
//            showGuidView1()
        }
        binding.buttonFirst.setOnClickListener {
//            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                .setAction("Action", null).show()
//            showGuidView1()
            Toast.makeText(baseContext,"哈哈，点击",Toast.LENGTH_SHORT).show()
        }

        val mOptionsItems: MutableList<String> = ArrayList()
        mOptionsItems.add("我的第一周")
        mOptionsItems.add("我的第二周")
        mOptionsItems.add("我的第三周")
        mOptionsItems.add("我的第四周")
        mOptionsItems.add("我的第五周")
        binding.wheelView.setCyclic(false)
        binding.wheelView.adapter = object :WheelAdapter<String>{
            override fun getItemsCount(): Int {



                return mOptionsItems.size
            }

            override fun getItem(index: Int): String {

               return mOptionsItems[index]
            }

            override fun indexOf(o: String?): Int {

                 return -1
            }

        }

        testSensor()


      val   alarmManagerUtils = AlarmManagerUtils.getInstance(this)
        alarmManagerUtils.createGetUpAlarmManager()

        binding.btnArm.setOnClickListener {

            alarmManagerUtils.getUpAlarmManagerStartWork()
        }
        Thread{
            Thread.sleep(2000)
            binding.btnArm.text = "21222222231"
        }.start()
    }

    override fun onResume() {
        super.onResume()

    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
//        menuInflater.inflate(R.menu.menu_main, menu)
        return true

    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration)
                || super.onSupportNavigateUp()
    }


    private fun showGuidView1(){

        NewbieGuide.with(this)
            .setLabel("guide1")
            //.setShowCounts(3)//控制次数
            .alwaysShow(true)//总是显示，调试时可以打开
            .addGuidePage(GuidePage.newInstance()
                .addHighLight(binding.buttonFirst)
                .setLayoutRes(R.layout.activity_main))
            .show();
    }


    fun timeStamp2Date(time: Long, format: String?): String? {
        var format = format
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss"
        }
        val sdf = SimpleDateFormat(format)
        return sdf.format(Date(time))
    }


//    测试距离传感器
      fun testSensor() {

    //1.获取SensorManager管理对象
    var sm = getSystemService(SENSOR_SERVICE)
    //2.获取据传感器对象
    if (sm is SensorManager) {
        var mProximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY)

        //3.给Sensor注册监听事件
        sm.registerListener(object : SensorEventListener{
            @SuppressLint("InvalidWakeLockTag")
            override fun onSensorChanged(event: SensorEvent?) {

                //获取event接收的数据
                var values = event?.values
                //获取距离传感器的距离
                var dis = values
                //获取最大距离getMaximumRange（）,系统固定值
                val maxAccuracy = mProximity.maximumRange
                Log.e("tag", "maxAccuracy-->$maxAccuracy")
                Log.e("tag", "dis-->${dis?.get(0)}")
//                Log.e("tag", "dis-->${dis?.get(1)}")
//                Log.e("tag", "dis-->${dis?.get(2)}")
//                Log.e("tag", "dis-->${dis?.get(3)}")
                if (dis?.get(0)!! < maxAccuracy){

//                    val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
//                    val wakeLock: PowerManager.WakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "TAG")

                    val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
                    val wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag")

//                    wakeLock.setReferenceCounted(false)
//                    wakeLock.acquire(1000L )
//                    wakeLock.release()
                    wakeLock.acquire()


                }

              }

            override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {

            }

        }, mProximity, SensorManager.AXIS_X)

        }
   }


     fun test(){

         rx.Observable.interval(1, TimeUnit.MINUTES)
             .observeOn(AndroidSchedulers.mainThread())
             .subscribeOn(rx.schedulers.Schedulers.io())
             .subscribe { aLong: Long ->
//
             }

           testKotlin {
               test()
           }


     }



    private fun testKotlin(test: Test.() -> Unit){




    }

    //扩展函数的定义
    private fun Test.test1(){

//        test()
        Log.e("tag","测试扩展函数")
    }


}